package jco3.JCoClientProgramming;

import javax.management.RuntimeErrorException;

import org.junit.Test;

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoField;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoRepository;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

public class RFC {
	public void getCompanyCodeDetail(String cocd) throws JCoException{
		// JCoDestination instance represents the backend SAP system
		JCoDestination dest = JCoDestinationManager.getDestination("ECC");
		
		 // JCoFunction instance is the FM in SAP we will use
		JCoRepository repository = dest.getRepository();
		JCoFunction fm = repository.getFunction("ZHRRFC_NAME_GET_PERNR");
		if(fm == null) {
			throw new RuntimeException("Function does not exists in SAP system.");
		}
		
		// set import parameter(s)
		fm.getImportParameterList().setValue("P_PERNR", "XXX");
		fm.getImportParameterList().setValue("P_NAME", "XXX");
		
		// call function
		fm.execute(dest);
		
		// get company code detail from exporting parameter 'COMPANYCODE_DETAIL'
		JCoTable cocdDetail  = fm.getTableParameterList().getTable("T_PERNR");
		this.printStructure(cocdDetail);
	}
	
	private void printStructure(JCoTable jcoStru) {
		for(JCoField field: jcoStru) {
			System.out.println(String.format("%s\\t%s", field.getName(),field.getString()));
		}
		for (int i = 0; i < jcoStru.getMetaData().getFieldCount(); i++){
	        System.out.println(String.format("%s\\t%s", 
	        		jcoStru.getMetaData().getName(i),
	        		jcoStru.getString(i)));
	    }
	}
	
	@Test
	public void test() throws JCoException{
		this.getCompanyCodeDetail("Z900");
	}
}
